<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT">










<meta name="description" content="&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;在Android开发中，我们一般使用Sdk提供的API进行开发，开发语言可以是Java和Kotlin。同时Android还为我们提供了NDK。NDK是什么呢？NDK是Android系统为我们提供的一个工具，通过NDK，我们可以很方便的调用C++代码。我们知道不同的Android设备之间差异性很大。它们的底层是有很大差异的，比如arm和x86,平台不一">
<meta property="og:type" content="article">
<meta property="og:title" content="NDK初体验">
<meta property="og:url" content="http://yoursite.com/2020/03/03/Android/Ndk初体验/index.html">
<meta property="og:site_name" content="zlb技术小栈">
<meta property="og:description" content="&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;在Android开发中，我们一般使用Sdk提供的API进行开发，开发语言可以是Java和Kotlin。同时Android还为我们提供了NDK。NDK是什么呢？NDK是Android系统为我们提供的一个工具，通过NDK，我们可以很方便的调用C++代码。我们知道不同的Android设备之间差异性很大。它们的底层是有很大差异的，比如arm和x86,平台不一">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-03-03T12:13:24.934Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="NDK初体验">
<meta name="twitter:description" content="&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;在Android开发中，我们一般使用Sdk提供的API进行开发，开发语言可以是Java和Kotlin。同时Android还为我们提供了NDK。NDK是什么呢？NDK是Android系统为我们提供的一个工具，通过NDK，我们可以很方便的调用C++代码。我们知道不同的Android设备之间差异性很大。它们的底层是有很大差异的，比如arm和x86,平台不一">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2020/03/03/Android/Ndk初体验/">





  <title>NDK初体验 | zlb技术小栈</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zlb技术小栈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/03/03/Android/Ndk初体验/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="LiboZhang">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zlb技术小栈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">NDK初体验</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-03-03T20:13:24+08:00">
                2020-03-03
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android/" itemprop="url" rel="index">
                    <span itemprop="name">Android</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>&nbsp;&nbsp;&nbsp;&nbsp;在Android开发中，我们一般使用Sdk提供的API进行开发，开发语言可以是Java和Kotlin。同时Android还为我们提供了NDK。NDK是什么呢？NDK是Android系统为我们提供的一个工具，通过NDK，我们可以很方便的调用C++代码。我们知道不同的Android设备之间差异性很大。它们的底层是有很大差异的，比如arm和x86,平台不一致导致驱动程序是不一样的。这样我们在调用不同平台的时候就得写很多套代码，NDK给我们提供了一个交叉编译的功能，可以同时编译支持多个平台的代码。<br>另外C++的运行效率是比较高的，所以一些对性能要求比较高的地方就可以使用NDK开发。利用NDK我们也可以很方便操作一些底层API,NDK编译出来的是二进制文件，反编译比较困难，从代码安全的角度上来说是比较安全的。<br>总的来说NDK有一下几个优点：<br>1.高性能<br>2.方便的操作底层<br>3.反编译难度大，代码安全<br>&nbsp;&nbsp;&nbsp;&nbsp;但是NDK开发的难度比较大，所以一般只是部分模块使用NDK。<br>下面我们开始使用NDK开发。<br>1.搭建环境，安装Android Studio，利用SDK Manager安装NDK,CMAKE,LLDB。<br>2.新建项目。在新建项目的时候勾选C++支持就可以直接创建了。对于已有项目需要按后续操作添加配置<br>3.在module目录下创建CMakeLists.txt文件，</p>
<pre><code>#cmake最低版本
cmake_minimum_required(VERSION 3.4.1) 
add_library( 
        # 库的名称
         native-lib
        # 库的类型
         SHARED

    # NDK源文件路径
    src/main/cpp/native-lib.cpp)
    find_library( # Sets the name of the path variable.
          log-lib

          # Specifies the name of the NDK library that
          # you want CMake to locate.
          log )
    target_link_libraries( # Specifies the target library.
                   native-lib

                   # Links the target library to the log library
                   # included in the NDK.
                   ${log-lib} )
</code></pre><p>4.在main目录下创建cpp目录<br>5.添加gradle配置<br>defaultConfig{<br> externalNativeBuild {<br>            cmake {<br>                cppFlags “-std=c++14”<br>                abiFilters ‘arm64-v8a’,’armeabi-v7a’,’x86’,’x86_64’<br>            }<br>        }<br>}</p>
<p>android{<br>     externalNativeBuild {<br>        cmake {<br>            path “CMakeLists.txt”<br>        }<br>    }<br>}</p>
<p>6.编写代码<br>1）Java层代码<br>package com.zlb.ndkdemo;</p>
<p>import android.support.v7.app.AppCompatActivity;<br>import android.os.Bundle;<br>import android.view.View;<br>import android.widget.Button;<br>import android.widget.Toast;</p>
<p>public class MainActivity extends AppCompatActivity {</p>
<pre><code>private Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn = findViewById(R.id.btn);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(MainActivity.this, getString(), Toast.LENGTH_LONG).show();
        }
    });

}

static {
    System.loadLibrary(&quot;native-lib&quot;);
}
public native String getString();
</code></pre><p>}</p>
<p>2）cpp代码</p>
<p>#include &lt;jni.h&gt;</p>
<p>#ifdef __cplusplus<br>extern “C” {</p>
<p>JNIEXPORT jstring JNICALL Java_com_zlb_ndkdemo_MainActivity_getString(JNIEnv <em>env, jobject type) {<br>//    return (</em>env)-&gt;NewStringUTF(env,”aaaa”);<br>    return env-&gt;NewStringUTF(“aaa”);<br>}<br>}</p>
<p>#endif<br>7.运行一下就能看到效果了</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/03/03/Java/java四种引用/" rel="next" title="Java四种引用">
                <i class="fa fa-chevron-left"></i> Java四种引用
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/03/03/Java/设计模式/单例模式/" rel="prev" title="单例模式">
                单例模式 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">LiboZhang</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">10</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">LiboZhang</span>

  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
